﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZhCun.CodeBuilder.DBModel;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;

namespace ZhCun.CodeBuilder.BLL
{
    class CodeConfigBLL : BaseBLL
    {
        ApiResult<string> VerifyModel(TCodeConfig model, bool isAdd)
        {
            if (model.Caption.IsEmpty())
            {
                return RetErr("Caption", "标题不能为空");
            }
            if (model.NameSpace.IsEmpty())
            {
                return RetErr("NameSpace", "命名控件不能为空");
            }
            if (model.SavePath.IsEmpty())
            {
                return RetErr("SavePath", "保存路径不能为空");
            }
            if (model.ConnString.IsEmpty())
            {
                return RetErr("ConnString", "连接字符串不能为空");
            }
            if (model.DBType.IsEmpty())
            {
                return RetErr("DBType", "数据库类型不能为空");
            }
            if (DB.QueryExist<TCodeConfig>(s => s.Id != model.Id && s.Caption == model.Caption))
            {
                return RetErr("Caption", "标题已经存在");
            }
            return RetOK("", "");
        }

        public ApiResult<string> Add(TCodeConfig model)
        {
            var r = VerifyModel(model, true);
            if (!r)
            {
                return r;
            }
            model.Id = NewId();
            DB.Insert(model);
            return RetOK(model.Id, "新增成功");
        }

        public ApiResult<string> Edit(TCodeConfig model)
        {
            var r = VerifyModel(model, false);
            if (!r)
            {
                return r;
            }
            var ret = DB.Update(model);
            if (ret.RowCount == 1)
            {
                return RetOK("", "修改成功");
            }
            else
            {
                return RetOK("", "修改失败");
            }
        }

        public ApiResult Del(TCodeConfig model)
        {
            var ret = DB.Delete<TCodeConfig>(s => s.Id == model.Id);
            if (ret.RowCount == 1)
            {
                return RetOK("更新成功");
            }
            else
            {
                return RetErr("更新失败");
            }
        }

        public ApiResultList<TCodeConfig> GetList(ArgPageData arg)
        {
            return
            GetPagerList<TCodeConfig>(arg, (query) =>
            {
                if (arg.SearchVal.IsNotEmpty())
                {
                    var likeStr = arg.SearchValLike;
                    query.WhereAnd(s => s.WEx_Like(s.Caption, likeStr));
                }
            });
        }
    }
}
